from django.shortcuts import render, redirect

from .models import Author, Blog
from .forms import AuthorForm, BlogForm


# Create your views here.

def index(request):
    authors = Author.objects.all()
    blogs = Blog.objects.all()
    return render(request, 'blog2_index.html', {'authors': authors, 'blogs': blogs})


def add_author(request):
    if request.method == "GET":
        form = AuthorForm()
        return render(request, 'add_author.html', {"form": form})
    elif request.method == "POST":
        form = AuthorForm(request.POST)
        if form.is_valid():
            author = Author(**form.cleaned_data)
            author.save()
        else:
            return render(request, 'add_author.html', {"form": form})
        return redirect('blog2:index')


def author(request, id):
    """
    详情页
    :param request:
    :return:
    """
    author = Author.objects.get(id=id)

    return render(request, 'author.html', {"author": author})


def add_blog(request):
    if request.method == "GET":
        form = BlogForm()
        return render(request, 'add_blog.html', {"form": form})
    elif request.method == "POST":
        form = BlogForm(request.POST)
        if form.is_valid():
            blog = Blog(**form.cleaned_data)
            blog.save()
        else:
            return render(request, 'add_blog.html', {"form": form})
        return redirect('blog2:index')


def blog(request, id):
    blog = Blog.objects.get(id=id)

    return render(request, 'blog2_blog.html', {"blog": blog})
